package wowmobileclient;

import java.io.IOException;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.Item;
import javax.microedition.lcdui.TextField;
import javax.microedition.lcdui.game.GameCanvas;
import javax.microedition.lcdui.game.TiledLayer;

public class Canvas extends GameCanvas implements Runnable {
    private Client client;
    private FightView fightview;
    private Image tiled;
    private Hud hud;
    private boolean gameRunning;
    private TiledLayer layer;
    private TiledLayer layer_players;
    private int width;
    private int height;
    private int level = 0;
    private boolean menu;
    public int gameX = 100;
    public int gameY = 100;
    public OnlineUsers users;
    public int[][] items = new int[gameX][gameY];
    public int[][] users_array = new int[gameX][gameY];
    private final int BLOCKSIZE = 16;
    static final int FREESPACE = 0;
    static final int GAMERDOWN = 1;
    static final int GAMERUP = 2;
    static final int GAMERRIGHT = 3;
    static final int GAMERLEFT = 4;
    static final int CAVE = 5;
    static final int GRASS = 6;
    static final int HIGHGRASS = 7;
    static final int PASSAGE = 8;
    static final int ROAD = 9;
    static final int ROCK = 10;
    static final int SAND = 11;
    static final int TREE = 12;

    private int lastKey;
    private final TextField LoginTxt;
    private final Command okCmd;
    private boolean invaiting;


    private final Form LoginFrm;



    public Canvas(Client client) throws IOException {
        super(true);
        this.client = client;
        setFullScreenMode(true);
        width = getWidth();
        height = getHeight();
        menu=false;
        hud=new Hud(getGraphics(), width, height);
        fightview = new FightView(getGraphics(), width, height, BLOCKSIZE);

        tiled = Image.createImage("/tiled.png");
        layer = new TiledLayer(gameX, gameY, tiled, BLOCKSIZE, BLOCKSIZE);
        readBoard();
        layer_players = new TiledLayer(gameX, gameY, tiled, BLOCKSIZE, BLOCKSIZE);

        users = new OnlineUsers(this);

        LoginTxt = new TextField("Player:", "", 50, TextField.ANY);
        LoginTxt.setString("babcia");
        okCmd = new Command("OK", Command.OK, 0);
        LoginFrm = new Form("Invite", new Item[] {LoginTxt});
        LoginFrm.addCommand(okCmd);
        LoginFrm.setCommandListener(client);
        invaiting=false;
    }

    public void run() {
        boolean isFight=false;
        int keyState;
        String coordinate;
        String answer;
        String players;
        int[] startFight={};
        String startFight2="";

        while (gameRunning) {
            keyState= getKeyStates();
            if(keyState==0)
            {
                keyState=lastKey;
                lastKey=0;
            }
            
            if(!isFight)
            {

                try
                {
                    players=client.getC().getPlayers();
                    System.out.println("Players: "+players);
                    users.addFromString(players);
                }
                catch (Exception e)
                {
                    System.err.println("Blad przy pobieraniu playerow:" + e);
                }
                moveDwarf(keyState);
                try
                {
                    coordinate=client.getC().getAnswer();
                    answer = client.getC().getAnswer();
                }
                catch (IOException ex)
                {
                    ex.printStackTrace();
                    return;
                }
                if (answer.startsWith("T"))
                {
                    isFight=true;
                    try {
                        startFight=client.getC().getStartFight();
                        startFight2=client.getC().getAnswer();
                        // 
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                }
                else if(coordinate.startsWith("T"))
                {
                    isFight=true;
                    startFight=client.getC().splitStartFight(answer);
                    try
                    {
                        startFight2=client.getC().getAnswer();
                    }
                    catch(IOException ex)
                    {
                        ex.printStackTrace();
                    }
                }
                
                try
                {


                    if(!isFight)
                    {
                        drawLayer(false,coordinate);
                        if(menu)
                        {
                            hud.drawMenu();
                            flushGraphics();
                        }
                        Thread.sleep(100);
                    }
                    else
                    {
                        fightview.draw(startFight[0],startFight[1]);
                        flushGraphics();
                    }
                }
                catch (InterruptedException interruptedexception)
                {
                    stop();
                }catch (NumberFormatException ex)
                {
                    stop();
                }
            }
            else
            {
                new Fight(fightview,client, this, startFight, startFight2).fight();
                isFight=false;
            }
            
        }
    }

    public void readBoard() {
        String b = new String("");
        try {
            b = client.getC().getArea();
        } catch (Exception ex) {
            System.err.println("Problem przy wczytaniu planszy:" + ex);
        }

        String[] board_lines = SplitString.split(b, "\n");
        for (int i = 0; i < board_lines.length; i++) {
            String[] tmp = SplitString.split(board_lines[i], ",");
            for (int j = 0; j < tmp.length; j++) {
                try {
                    items[i][j] = Integer.parseInt(tmp[j]);
                } catch (NumberFormatException ex) {
                    items[i][j] = 0;
                }
            }
        }

    }

    public void start() {
        gameRunning = true;
        Thread thread = new Thread(this);
        thread.start();
    }

    public void stop() {
        gameRunning = false;
    }

    public void restart(int[][] items) {
        try {
            stop();
            Thread.sleep(220);
   
           // drawLayer(true, );
            Thread.sleep(1000);
        } catch (InterruptedException ex) {
        }
    }

    public int getLevel() {
        return level;
    }

    public void setLevel(int l) {
        level = l;
    }

    public void moveDwarf(int keyState) {
        int dx = 0, dy = 0;
        Action a = new Action();
        if(!menu)
        {
            if ((keyState == RIGHT_PRESSED) ) {
                dx = 1;
                a.setMove(Action.RIGHT);
            } else if ((keyState == LEFT_PRESSED) ) {
                dx = -1;
                a.setMove(Action.LEFT);
            } else if ((keyState == DOWN_PRESSED) ) {
                dy = 1;
                a.setMove(Action.DOWN);
            } else if ((keyState == UP_PRESSED)) {
                dy = -1;
                a.setMove(Action.UP);
            } else if((keyState == 512)) {
                a.setMove(6);
            }
            try
            {
                client.getC().sendAction(a);
            }
            catch (Exception e)
            {
                System.err.println("Blad przy wysylaniu akcji:" + e);
            }
        }
        else
        {
            System.out.println(keyState);
            if(keyState == 512)
            {
                client.getC().sendString("51");
                String tmp;
                try {
                    tmp = client.getC().getAnswer();
                    System.out.println(tmp);
                } catch (IOException ex) {
                    ex.printStackTrace();
                    return;
                }
                PlayerStats ps=new PlayerStats(tmp);
                hud.drawStats(ps);
                flushGraphics();
                freeze();
            }
            else if(keyState == 50)
            {

                client.getC().sendString("51");
                String tmp;
                try {
                    tmp = client.getC().getAnswer();
                    System.out.println(tmp);
                } catch (IOException ex) {
                    ex.printStackTrace();
                    return;
                }
                PlayerStats ps=new PlayerStats(tmp);
                hud.drawMagic(ps);
                flushGraphics();
                freeze();
            }
            else if(keyState == 1024)
            {
                client.getC().sendString("51");
                String tmp;
                try {
                    tmp = client.getC().getAnswer();
                    System.out.println(tmp);
                } catch (IOException ex) {
                    ex.printStackTrace();
                    return;
                }
                PlayerStats ps=new PlayerStats(tmp);
                hud.drawEq(ps);
                flushGraphics();
                freeze();
            }
            else if(keyState== 52)
            {
                invaiting=true;
                client.getMainDisplay().setCurrent(LoginFrm);
                while(invaiting)
                    try {
                    Thread.sleep(10);
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                }
            }
            else if(keyState==54)
            {
                client.getC().sendString("53");
                String tmp;
                try
                {
                    tmp=client.getC().getAnswer();
                }
                catch (IOException ex) {
                    ex.printStackTrace();
                    return;
                }
                hud.drawQuest(tmp);
                flushGraphics();
                freeze();
            }
            else
            {
                try
                {
                    client.getC().sendAction(a);
                }
                catch (Exception e)
                {
                    System.err.println("Blad przy wysylaniu akcji:" + e);
                }
            }
        }

        if((keyState == 53))
            menu=!menu;

        

        
    }

    public void drawLayer(boolean end,String coordinate) throws NumberFormatException
    {
       int x = layer.getX(), y = layer.getY();
       int w = width / BLOCKSIZE, h = height / BLOCKSIZE;
       int w1 = w >> 1, w2 = (w >> 1) + (w & 1);
       int h1 = h >> 1, h2 = (h >> 1) + (h & 1);
       String[] tmp=SplitString.split(coordinate, " ");
       layer.setPosition(-(Integer.parseInt(tmp[0])-w1)*BLOCKSIZE, -(Integer.parseInt(tmp[1])-h1)*BLOCKSIZE);
       //layer_players.setPosition(x, y);

        Graphics g = getGraphics();
        g.setColor(0, 0, 0);
        g.fillRect(0, 0, getWidth(), getHeight());
        for (int j = 0; j < gameY; j++) {
            for (int i = 0; i < gameX; i++) {
                layer.setCell(i, j, items[i][j]);

                if (users_array[i][j] != 0) {
                    layer.setCell(i, j, users_array[i][j]);
                }
            }
        }
        layer.paint(g);
        flushGraphics();
    }

    protected void keyPressed(int keyCode)
    {
    //try catch  getGameAction as can legally throw an exception
        lastKey=keyCode;
    }

    public int getLastKey() {
        return lastKey;
    }

    public void setLastKey(int lastKey) {
        this.lastKey = lastKey;
    }

    private void freeze() {
        int key=0;
        while(key==0)
        {
            key= getKeyStates();
            if(key==0)
            {
                key=getLastKey();
                setLastKey(0);
            }
            try
            {
                Thread.sleep(10);
            }
            catch (InterruptedException ex)
            {
                ex.printStackTrace();
            }
        }
    }


    public Command getOkCmd() {
        return okCmd;
    }


    void invitePlayer()
    {
        String tmp=LoginTxt.getString();
        client.getC().sendString("52");
        client.getC().sendString(tmp);
        client.getMainDisplay().setCurrent(this);
        invaiting=false;
    }


}
